<template>
    <div class="home" v-if="userid">
        <div class="aboveBox">
            <el-descriptions title="用户信息" style="font-size: 20px !important ; color: black;">
                <el-descriptions-item label="用户昵称">{{ userinfo.name }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ userinfo.gender }}</el-descriptions-item>
                <el-descriptions-item label="年龄">{{ userinfo.age }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userinfo.user_phone }}</el-descriptions-item>
                <el-descriptions-item label="住址">{{ userinfo.user_site }}</el-descriptions-item>
            </el-descriptions>
            <el-button @click="handleEdit()">修改资料</el-button>
            <el-button @click="goLogin()">退出登录</el-button>
        </div>
        <div class="belowBox" v-if="guideList.length > 0">
            <span style="display: flex; justify-content: space-between;align-items: center;">
                <h2 style="margin: 20px;">我的攻略</h2>
                <el-button type="info" round style="height: 40px;margin: 0 20px;"
                    @click="showPublish()">发布攻略</el-button>
            </span>
            <el-col :span="8" v-for="(item, index) in guideList" :key="index">
                <el-card :body-style="{ padding: '0px', margin: '10px' }" style="overflow: hidden;margin: 5px;">
                    <img :src="item.guide_img[0]" class="image" @click="spotClick(item)">
                    <div style="padding: 14px;">
                        <span>《{{ item.guide_name }}》</span>
                        <span style="float: right;">
                            <i class="el-icon-edit" style="margin: 0 10px;" @click="guideUpdata(item)"></i>
                            <i class="el-icon-delete" @click="guideDelete(item._id)"></i>
                        </span>
                    </div>
                </el-card>
            </el-col>
        </div>
        <div class="belowBox" v-if="guideList.length <= 0">
            <span style="display: flex; justify-content: space-between;align-items: center;">
                <h2 style="margin: 20px;display: inline-block;width: 200px;">我的攻略</h2>
                <el-button type="info" round style="height: 40px;margin: 0 20px;"
                    @click="showPublish()">发布攻略</el-button>
            </span>
            <div style="width: 100%;font-size: 50px;text-align: center;margin-top: 100px;">
                暂无相关数据
            </div>
        </div>
        <el-dialog title="更改资料" :visible.sync="userFormVisible" width="30%">
            <el-form :model="form" ref="ruleForm">
                <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
                    <el-select v-model="form.gender" placeholder="请选择性别" style="text-align: left;">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
                    <el-input v-model="form.age" autocomplete="off" placeholder="年龄"></el-input>
                </el-form-item>
                <el-form-item label="电话" :label-width="formLabelWidth" prop="user_phone">
                    <el-input v-model="form.user_phone" autocomplete="off" placeholder="电话"></el-input>
                </el-form-item>
                <el-form-item label="地址" :label-width="formLabelWidth" prop="user_site">
                    <el-input v-model="form.user_site" autocomplete="off" placeholder="地址"></el-input>
                </el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form>
        </el-dialog>
        <el-dialog :title="guideChange === false ? '发布攻略' : '修改攻略'" :visible.sync="guideFormVisible" width="50%"
            @close="guideClose()">
            <el-form :model="guideform" ref="ruleguideForm">
                <el-form-item label="标题" :label-width="formLabelWidth" prop="guide_name">
                    <el-input v-model="guideform.guide_name" autocomplete="off" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="景点" :label-width="formLabelWidth" prop="guide_place">
                    <el-input v-model="guideform.guide_place" autocomplete="off" placeholder="景点"></el-input>
                </el-form-item>
                <el-form-item label="攻略信息" :label-width="formLabelWidth" prop="guide_information">
                    <el-input type="textarea" v-model="guideform.guide_information" autocomplete="off"
                        placeholder="攻略信息" maxlength="500" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="图片信息" :label-width="formLabelWidth">
                    <el-upload style="margin:10px 0px!important;" :action="uploadUrl" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :headers="headerObj"
                        :on-success="handleSuccess" :file-list="fileList">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
                <el-button type="primary" @click="publish()">提交</el-button>
                <el-button @click="resetguideForm('ruleguideForm')">重置</el-button>
            </el-form>
        </el-dialog>
        <el-backtop :right="60" :bottom="100" />
    </div>
    <div v-else>
        <div style="width: 100%;text-align: center;font-size: 40px;margin-top: 20%;">尚未登录，请先登录后再查看。</div>
    </div>
</template>

<script>
import api from '@/api'
export default {
    data() {
        return {
            pageIndex: 1,
            pageSize: 10,
            total: 10,
            spotsID: '',
            spotname: '',
            userinfo: {},
            userid: '',
            lastTime: 0,
            guideList: [],
            headerObj: {
                file: '',
            },
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            uploadUrl: "http://localhost:4000/file/uploadImg",
            fileList: [],
            userFormVisible: false,
            guideFormVisible: false,
            guideChange: false,
            form: {
                name: "",
                user_account: "",
                user_password: "",
                gender: "",
                age: "",
                user_phone: "",
                user_site: "",
            },
            guideform: {
                guide_name: "",
                guide_information: "",
                guide_place: "",
                guide_createname: "",
                guide_createtime: "",
                guide_createid: "",
                guide_img: []
            },
            guideinfo: {
                guide_name: "",
                guide_information: "",
                guide_place: "",
                guide_createname: "",
                guide_createtime: "",
                guide_createid: "",
                guide_img: []
            },
            formLabelWidth: '80px'
        };
    },
    mounted() {
        this.userid = localStorage.userid;
        this.getGuideList();
        this.getUserinfo();
    },
    methods: {
        /**退出登录，清除本地存储，刷新页面 */
        goLogin() {
            localStorage.clear();
            location.reload();
        },
        async getGuideList() {
            this.guideList = [];
            let res = await api.getGuide({ pageIndex: this.pageIndex, pageSize: this.pageSize })
            if (res?.code == 200) {
                for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].guide_createid === this.userid) {
                        this.guideList.push(res.data[i]);
                    }
                }
            } else {
                this.guideList = [];
            }
        },
        async getUserinfo() {
            let res = await api.findUser({ id: this.userid })
            if (res?.code == 200) {
                this.userinfo = res.data;
                localStorage.username = res.data.name;
            } else {
                this.userinfo = {};
            }
        },
        spotClick(item) {
            localStorage.guideid = item._id
            this.$router.push({
                path: '/showguideview'
            })
        },
        async handleOk() {
            this.userFormVisible = false;
            let res = await api.updateUsers({ ...this.form })
            if (res?.code == 200) {
                this.$message({
                    message: res.message,
                    type: 'success'
                });
                this.getUserinfo();

            } else {
                this.$message.error(res.message);
            }
        },
        handleEdit() {
            this.userFormVisible = true;
            this.form = { ...this.userinfo };
        },
        submitForm(formName) {
            const now = new Date().getTime();
            if (now - this.lastTime > 1000) { // 如果距离上次点击超过 1000 毫秒  
                this.lastTime = now;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.handleOk();
                    } else {
                        return false;
                    }
                });
            }
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        showPublish() {
            this.guideChange = false;
            this.guideFormVisible = true;
        },
        /**获取上传的时间的 */
        gettime() {
            let now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth() + 1;
            month = month < 10 ? '0' + month : month;
            let date = now.getDate();
            date = date < 10 ? '0' + date : date;
            let hours = now.getHours();
            hours = hours < 10 ? '0' + hours : hours;
            let minutes = now.getMinutes();
            minutes = minutes < 10 ? '0' + minutes : minutes;
            let seconds = now.getSeconds();
            seconds = seconds < 10 ? '0' + seconds : seconds;
            let formattedDate = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
            this.guideform.guide_createtime = formattedDate;
            this.guideform.guide_createid = this.userinfo._id;
            this.guideform.guide_createname = this.userinfo.name;
        },
        /**发布和修改公用，通过guideChange参数判断是修改还是发布 */
        publish() {
            const now = new Date().getTime();
            if (now - this.lastTime > 1000) {
                this.lastTime = now;
                if (this.guideChange) {
                    if (this.guideform.guide_img.length == 0) {
                        this.$message.error('请上传图片');
                    } else {
                        this.dialogFormVisible = false;
                        this.gettime();
                        this.fileList = [];
                        setTimeout(async () => {
                            let res = await api.updateGuide({ ...this.guideform })
                            if (res?.code == 200) {
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                });
                                this.getGuideList();
                                this.guideFormVisible = false;
                                this.guideChange = false;
                                this.guideform = { ...this.guideinfo };
                            } else {
                                this.$message.error(res.message);
                            }
                        }, 0);
                    }
                } else {
                    if (this.guideform.guide_img.length == 0) {
                        this.$message.error('请上传图片');
                    } else {
                        this.gettime();
                        setTimeout(async () => {
                            let res = await api.addGuide({ ...this.guideform })
                            if (res?.code == 200) {
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                });
                                this.getGuideList();
                                this.guideFormVisible = false;
                            } else {
                                this.$message.error(res.message);
                            }
                        }, 0);
                    }
                }
            }
        },
        /**修改 */
        guideUpdata(item) {
            this.guideFormVisible = true;
            this.guideform = { ...item };
            this.guideChange = true;
        },
        handleSuccess(response, file, fileList) {
            this.guideform.guide_img.push(response.url);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleRemove(file) {
            let index = this.guideform.guide_img.indexOf(file.response.url);
            if (index !== -1) {
                this.guideform.guide_img.splice(index, 1);
            }
        },
        resetguideForm(ruleguideForm) {
            this.$refs[ruleguideForm].resetFields();
        },
        async guideDelete(_id) {
            let res = await api.delGuide({ _id });
            if (res?.code == 200) {
                this.$message({
                    message: res.message,
                    type: 'success'
                });
                this.getGuideList();
            } else {
                this.$message.error(res.message);
            }
        },
        guideClose() {
            this.guideFormVisible = false;
            this.guideform = { ...this.guideinfo };
        }
    }
};
</script>

<style scoped>
.home {
    width: 100%;
    height: 100vh;
}

.aboveBox {
    width: 85%;
    padding: 20px;
    margin: 10px auto;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: flex-end;
    border: 1px solid #ddd;

}

.belowBox {
    width: 85%;
    height: 70vh;
    padding: 20px;
    margin: 10px auto;
    background-color: #ddd;
    border-radius: 10px;
    overflow-y: scroll;
}

.belowBox::-webkit-scrollbar {
    display: none;
}

.aboveBox:deep(.el-descriptions__title) {
    font-size: 30px !important;
}

.aboveBox:deep(el-descriptions-item__cell) {
    color: black;
}

.img {
    width: 40%;
    height: 500px;
    overflow: hidden;
    border-radius: 20px;

}

.image {
    width: 100%;
    height: 400px;
    object-fit: cover;
}

.el-image {
    width: 100%;
    height: 100%;
}
</style>